package com.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.web.constant.Constant;
import com.web.vo.ResultVO;

public abstract class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public abstract boolean before(HttpServletRequest request, HttpServletResponse response,Map<String, Object> data);

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

		if (request.getMethod().equals("OPTIONS")) {
			return;
		}
		
		response.setHeader("content-type", "application/json;charset=utf-8");
		request.setCharacterEncoding("utf-8");

		Map<String, Object> data = null;
		try {
			// 检测是否为多媒体上传 getInputStream 会预处理 导致后面无法获取上传的文件
			if (!ServletFileUpload.isMultipartContent(request)) {
				data = JSONObject.parseObject(request.getInputStream(), Map.class);
			}
		} catch (Exception e) {
		}

		boolean flag = before(request, response,data);
		if (!flag) return;

//		String methodName = request.getParameter("method");
		String[] strs = request.getRequestURI().split("/");
		String methodName = strs[strs.length - 1];
		try {
			Class<? extends BaseServlet> clazz = this.getClass();
			Method m = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class, Map.class);
			Object result = m.invoke(this, request, response, data);
			returnJSON(response, result);
		} catch (NoSuchMethodException e) {
			ResultVO errres = new ResultVO();
			errres.setStatus(Constant.ERROR_STATUS);
			errres.setMessage("路径错误");
			returnJSON(response, errres);
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			ResultVO errres = new ResultVO();
			errres.setStatus(Constant.ERROR_STATUS);
			errres.setMessage("代码错误1");
			returnJSON(response, errres);
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			ResultVO errres = new ResultVO();
			errres.setStatus(Constant.ERROR_STATUS);
			errres.setMessage("代码错误2");
			returnJSON(response, errres);
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			ResultVO errres = new ResultVO();
			errres.setStatus(Constant.ERROR_STATUS);
			errres.setMessage("参数错误");
			returnJSON(response, errres);
			e.printStackTrace();
		}
	}

	protected void returnJSON(HttpServletResponse response, Object data){
		try {
			response.getWriter().print(JSONObject.toJSONString(data, SerializerFeature.WriteMapNullValue));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
